package queue.block;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author czt
 * @version 1.0
 * @since 2024/12/23
 */
public class TestThreadUnsafe {
    private final String[] array = new String[10];
    private int tail = 0;
    private int size = 0;
    ReentrantLock lock = new ReentrantLock(); // 锁对象
    Condition tailWaits = lock.newCondition(); // 条件变量对象 集合

    public void offer(String e) throws InterruptedException {
        lock.lockInterruptibly(); // 加锁一般写在try块外面
        try {
            // 需要被保护的代码写在try块里面
            while (isFull()) { // 用while防止虚假唤醒
                // 满了该做的事，offer线程阻塞
                tailWaits.await(); // 当前线程加入到 tailWaits，并且让此线程阻塞 tailWaits.signal()唤醒
            }
            array[tail] = e;
            if (++tail == array.length) {
                tail = 0;
            }
            size++;
        }finally {
            // 释放锁的方法一般写在finally里
            lock.unlock();
        }
    }

    private boolean isFull() {
        return size == array.length;
    }

    @Override
    public String toString() {
        return Arrays.toString(array);
    }

}
